#import "AliyunPlugin.h"
#import <AliyunIdentityManager/AliyunIdentityPublicApi.h>
#import <AliyunIdentityManager/PoPGatewayNetwork.h>
#import <ZolozUtility/NSObject+APBJSON.h>

// static UIViewController *viewCtr;

@implementation AliyunPlugin
+ (void)registerWithRegistrar:(NSObject<FlutterPluginRegistrar>*)registrar {
  FlutterMethodChannel* channel = [FlutterMethodChannel
      methodChannelWithName:@"aliyun_plugin"
            binaryMessenger:[registrar messenger]];
  AliyunPlugin* instance = [[AliyunPlugin alloc] init];
  // viewCtr = (__bridge UIViewController*)registrar.accessibilityNavigationStyle;
  [AliyunSdk init];
  [registrar addMethodCallDelegate:instance channel:channel];
}
- (void)handleMethodCall:(FlutterMethodCall*)call result:(FlutterResult)result {
  NSLog(@"method:%@",call.method);
  if ([@"metaInfo" isEqualToString:call.method]) {
    NSDictionary* metaInfo = [AliyunIdentityManager getMetaInfo];
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:metaInfo options:0 error:0];
    NSString *metaInfoStr = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    result(metaInfoStr);
  } else if ([@"face" isEqualToString:call.method]) {
    NSString *certifyId = call.arguments[@"certifyId"];
    NSMutableDictionary  *extParams = [NSMutableDictionary new];
    UIViewController* viewController = [UIApplication sharedApplication].keyWindow.rootViewController;
    if ([viewController isKindOfClass:[UINavigationController class]]) {
      [((UINavigationController*)viewController) popViewControllerAnimated:NO];
    }
    NSLog(@"viewController______________:%@",viewController);
     @try {
        [extParams setValue:viewController forKey:@"currentCtr"];
        [[AliyunIdentityManager sharedInstance] verifyWith:certifyId extParams:extParams onCompletion:^(ZIMResponse *response) {
          dispatch_async(dispatch_get_main_queue(), ^{
              NSLog(@"RESPONSE:%@",response);
              if(response.code == 1000){
                result(@"success");
              }else{
                result(@"fail");
              }
          });
         
      }];
    }
    @catch (NSException *exception) {
        NSLog(@"捕捉异常：%@,%@",exception.name,exception.reason);
    }
    
  }else if ([@"init" isEqualToString:call.method]) {
    result(@"inited");
  }else {
    result(FlutterMethodNotImplemented);
  }
}

@end
